import socket
import threading
from PyQt5.QtCore import pyqtSignal, QObject
from app.utils.json_utils import parse_json, to_json
from app.utils.logger import ETCLogger

# 初始化日志记录器
logger = ETCLogger()

class Server(QObject):
    new_message = pyqtSignal(str)  # 用于发送新消息的信号

    def __init__(self, host="0.0.0.0", port=5555, max_clients=10, serial_manager=None):
        super().__init__()
        self.host = host
        self.port = port
        self.max_clients = max_clients
        self.serial_manager = serial_manager
        self.clients = []

    def start(self):
        """启动服务器"""
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind((self.host, self.port))
        self.socket.listen(self.max_clients)
        logger.tcp_log(f"Server started, listening on {self.host}:{self.port}")
        self.new_message.emit(f"Server started, listening on {self.host}:{self.port}")

        while True:
            client_socket, client_address = self.socket.accept()
            # logger.tcp_log(f"Client connected: {client_address}", ip=client_address[0])
            # self.new_message.emit(f"Client connected: {client_address}")
            client_thread = threading.Thread(
                target=self.handle_client,
                args=(client_socket,)
            )
            client_thread.start()
            self.clients.append(client_socket)

    def handle_client(self, client_socket):
        """处理客户端连接"""
        client_address = None
        try:
            # 获取客户端地址
            client_address = client_socket.getpeername()
            logger.tcp_log(f"Client connected: {client_address}", ip=client_address[0])
            self.new_message.emit(f"Client connected: {client_address}")

            while True:
                data = client_socket.recv(1024).decode("utf-8")
                if not data:
                    break

                # 记录接收的数据
                logger.tcp_log(f"<<< Received: {data}", ip=client_address[0])

                # 解析 JSON 数据
                command = parse_json(data)
                self.new_message.emit(f"Received command: {command}")
                response = self.process_command(command)

                # 发送响应
                client_socket.send(to_json(response).encode("utf-8"))
                self.new_message.emit(f"Sent response: {response}")
                logger.tcp_log(f">>> Sent: {response}", ip=client_address[0])
        except Exception as e:
            logger.tcp_log(f"Error processing client data: {e}", ip=client_address[0] if client_address else None)
        finally:
            # 关闭客户端连接
            client_socket.close()
            if client_address:
                logger.tcp_log(f"Client disconnected: {client_address}", ip=client_address[0])
                self.new_message.emit(f"Client disconnected: {client_address}")
            else:
                logger.tcp_log("Client disconnected: Unknown address")
                self.new_message.emit("Client disconnected: Unknown address")

    def process_command(self, command):
        """处理指令"""
        cmd = command.get("cmd", "").lower()
        if cmd == "power_on":
            from app.handlers.power_on_handler import PowerOnHandler
            handler = PowerOnHandler(self.serial_manager)
        elif cmd == "power_off":
            from app.handlers.power_off_handler import PowerOffHandler
            handler = PowerOffHandler(self.serial_manager)
        elif cmd == "next":
            from app.handlers.next_handler import NextHandler
            handler = NextHandler(self.serial_manager)
        elif cmd == "previous":
            from app.handlers.previous_handler import PreviousHandler
            handler = PreviousHandler(self.serial_manager)
        elif cmd == "get_electrical":
            from app.handlers.get_electrical_handler import GetElectricalHandler
            handler = GetElectricalHandler(self.serial_manager)
        else:
            return {"status": "error", "message": "Unknown command"}

        return handler.handle(command)